/**
 *Kugou Javascript Library V1.0.1
 *Release Date:2012.2.8
 */
String.prototype.getBytes = function() {
    var bytes = 0;
    for (var i = 0, l = this.length; i < l; i++) {
        if (this.charCodeAt(i) > 256) { bytes += 2; }
        else { bytes += 1; }
    }
    return bytes;
};

String.prototype.trim = function(){return this.replace(/^\s*|\s*$/g,"");};

String.prototype.intercept = function(length, appendStr) {
    var str = this;
    str = str.trim();
    if (str.getBytes() < length) return str;
    var countLen = 0;
    var charCount = 0;
    if (appendStr.length > 0) {
        length = length - appendStr.length;
    }
    for (var i = 0; i < str.length; i++) {
        if (this.charCodeAt(i) > 256) {
            countLen += 2;
        }
        else {
            countLen += 1;
        }
        if (countLen > length) {
            break;
        }
        charCount++;
    }
    return str.substr(0, charCount) + appendStr;
};

function sdnClick(num) {
	try {
		setTimeout(function(){
			(new Image()).src = "http://sdn.kugou.com/link.aspx?id=" + num + "&url=&t=" + Math.random();
		},0);
	} catch (ex) { }
};

var Kg = Kg || {
	/**
	 *浏览器判断
	 * @id UA
	 */
	UA:{
		Ie:!!document.all,
		Ie6:!!document.all && !window.XMLHttpRequest,
		Ie7:!!document.all && /msie 7.0/gi.test(window.navigator.appVersion),
		Ie8:!!document.all && /msie 8.0/gi.test(window.navigator.appVersion),
		FF:/firefox/gi.test(window.navigator.userAgent),
		Opera:/opera/gi.test(window.navigator.userAgent),
		Chrom:/Chrom/gi.test(window.navigator.userAgent)
	},
	/**
	 * 通过HTML元素的id获取Dom对象
	 * @id $
	 * @param {String | Object} HTML标签的id或者Dom对象，参数可多个
	 * @return {Object | Array} HTMLElement对象 或 HTMLElement对象组
	 */
	$:function(){
		var els = [];
		for(var i = 0,l = arguments.length; i < l; i++){
			var el = arguments[i];
			if(typeof el == "string") el = document.getElementById(el);
			if(l == 1) return el;
			els.push(el);				
		}
		return els;
	},
	/**
	 * 通过HTML元素的标签名获取Dom数组对象
	 * @id $T
	 * @param {String} HTML标签名称 --此项为可选
	 * @param {String | Object} HTML标签的id或者Dom对象 --此项为可选
	 * @return {Array} HTMLElement数组对象
	 */
	$T:function(tagName, el){
		var els = (this.$(el) || document).getElementsByTagName(tagName || "*");
		return this.$A(els);
	},
	/**
	 * 通过HTML元素的className获取Dom数组对象
	 * @id $C
	 * @param {String} HTML标签的class
	 * @param {String | Object} HTML标签的id或者Dom对象 --此项为可选
	 * @param {String} HTML标签名 --此项为可选
	 * @return {Array} Dom HTMLElement数组对象
	 */
	$C:function(name, el, tagName){
		var cEls = [], i =0;
		if(!!document.getElementsByClassName){
			var arr = this.$(el || document).getElementsByClassName(name);
			arr = this.$A(arr);
			if(tagName && tagName !== "*"){
				for(var l = arr.length; i < l; i++){
					(arr[i].tagName.toLowerCase() === tagName.toLowerCase()) && cEls.push(arr[i]);
				}
			} else {
				cEls = arr;
			}
		} else {
			for(var arr = this.$T(tagName, el), l = arr.length; i < l; i++){
				new RegExp("\\b" + name + "\\b","g").test(arr[i].className) && cEls.push(arr[i]);
			}
		}
		return cEls;
	},
	/**
	 * 将HTMLCOLLECTION转为ARRAY
	 * @id $A
	 * @param {String} HTMLElement对象组
	 * @return {Array} HTMLElement数组对象
	 */
	$A:function(args){
		var arr = [];
		for(var i = 0, l = args.length; i < l; i++){
			arr.push(args[i]);
		}
		return arr;
	},
	/**
	 * 继承对象（复制属性/方法）
	 * @id extend
	 * @param {Object} 被复制对象（子对象）
	 * @param {Object} 复制对象（父对象）
	 * @param {Boolean}  是否重写属性/方法
	 * @return {Object} 返回被复制对象（子对象）
	 */
	extend:function(target, souce, rewrite){
		for(var property in souce){
			if(rewrite)	target[property] = souce[property]; 
			else if(!target[property]) target[property] = souce[property]; 
		}
		return target;
	},
	/**
	 * 获取对象样式
	 * @id getStyle
	 * @param {Object} HTML标签的id或者Dom对象
	 * @param {String} 样式名字
	 * @return {String} 样式值
	 */
	getStyle:function(el,name){
		el = this.$(el);
		if(name === "float"){
			name = Kg.UA.Ie?"styleFloat":"cssFloat";
		}

		name = name.replace(/-(\w)/, function(a, b){
			return b.toUpperCase();
		});
		
		return Kg.UA.Ie?
			el.currentStyle[name]:
			window.getComputedStyle(el,null)[name];
	},
	/**
	 * 获取页面可视宽、高、滚动全高、滚动全宽、滚动高、滚动宽
	 * @id getBodySize
	 * @return {Object} 页面宽度值、高度值、滚动全高度值、滚动全宽度值、滚动高值、滚动宽值
	 */
	getBodySize:function(){
		if(document.compatMode == "BackCompat"){
			var clientH = document.body.clientHeight;
			var clientW = document.body.clientWidth;
			var scrollH = document.body.scrollHeight;
			var scrollW = document.body.scrollWidth;
			var scrollT = document.body.scrollTop;
			var scrollL = document.body.scrollLeft;
		} else if(document.compatMode == "CSS1Compat"){
			var clientH = document.documentElement.clientHeight;
			var clientW = document.documentElement.clientWidth;
			var scrollH = document.documentElement.scrollHeight;
			var scrollW = document.documentElement.scrollWidth;
			var scrollT = document.body.scrollTop || document.documentElement.scrollTop;
			var scrollL = document.body.scrollLeft || document.documentElement.scrollLeft;
		}
		return {cH:clientH,cW:clientW,sH:scrollH,sW:scrollW,sT:scrollT,sL:scrollL};
	},
	/**
	 * 获取HTMLElement对象与窗口边界的距离
	 * @id getXY
	 * @param {Object} HTML标签的id或者Dom对象
	 * @return {Object} 返回HTMLElement对象四边与窗口边界的距离
	 */
	getXY:function(el){
		el = this.$(el);
		var bodySize = this.getBodySize();
		var elRect = el.getBoundingClientRect();
		return {left:bodySize.sL + elRect.left,right:bodySize.sL + elRect.right,top:bodySize.sT + elRect.top,bottom:bodySize.sT + elRect.bottom};
	},
	/**
	 * 判断是否子孙后代关系
	 * @id isFather
	 * @param {String | Object} 父层DOM对象或者ID
	 * @param {String | Object} 子层DOM对象或者ID
	 * @param {Boolean} 是否允许2个DOM对象为同一个对象
	 * @return {Boolean} 返回两种是否子孙后代关系
	 */
	isFather:function (father, child, bol){
		father = this.$(father);
		child = this.$(child);

		if(bol && (father == child))
			return true;

		if(father.compareDocumentPosition)
			return father.compareDocumentPosition(child) == 20;

		while(child && child.parentNode){
			child = child.parentNode;
			if(child == father) return true;
		}
		return false;
	},
	/**
	 * 设置监听器
	 * @id addEvent
	 * @param {Object} 监听对象,HTML标签的id或者Dom对象
	 * @param {String} 监听类型
	 * @param {Function} 监听方法
	 */
	addEvent:function(obj,type,func){
		obj = this.$(obj);
		if(obj.addEventListener){
			obj.addEventListener(type,func,true);
		} else if(obj.attachEvent){
			obj.attachEvent("on" + type,func);
		} else {
			obj["on" + type] = func;
		}
	},
	/**
	 * 清除监听器
	 * @id removeEvent
	 * @param {Object} 监听对象,HTML标签的id或者Dom对象
	 * @param {String} 监听类型
	 * @param {Function} 监听方法
	 */
	removeEvent:function(obj,type,func){
		obj = this.$(obj);
		if(obj.removeEventListener){
			obj.removeEventListener(type,func,false);
		} else if(obj.detachEvent){
			obj.detachEvent("on" + type,func);
		} else {
			obj["on" + type] = null;
		}
	},
	/**
	 * 选择环境运行函数
	 * @id bind
	 * @param {Function} 执行函数
	 * @param {Object} 运行环境
	 * @return {Function} 返回一个已被绑定运行环境的函数
	 */
	bind:function(func,environment){
		var params = Array.prototype.slice.call(arguments,2);
		return function(){
			func.apply(environment,params.concat(Array.prototype.slice.call(arguments)));
		}
	},
	/**
	 * 停止事件冒泡
	 * @id stopEvent
	 * @param {Object} Event对象
	 * @return {Object} 返回Kg对象
	 */
	stopEvent:function(event){
		event = window.event || event;
		if(event.stopPropagation){
			event.stopPropagation();
		}else{
			event.cancelBubble = true;
		}
		return this;
	},
	/**
	 * 判断检测元素是否在数组内
	 * @id inArray
	 * @param {Array} 检测所在的数组
	 * @param {All} 检测元素 注意：不要比较内容相同但内存地址不同的元素
	 * @return {Boolean} 元素是否在数组内
	 */
	inArray:function(arr, compare){
		for(var i = 0,l = arr.length; i < l; i++){
			if(arr[i] === compare)	return true
		}
		return false;
	},
	/**
	 * 判断检测元素在数组内的位置
	 * @id indexOf
	 * @param {Array} 检测所在的数组
	 * @param {All} 检测元素 注意：不要比较内容相同但内存地址不同的元素
	 * @return {Number} 元素在数组内的位置，不存在该数组就返回-1
	 */
	indexOf:function(arr, compare){
		for(var i = 0,l = arr.length; i < l; i++){
			if(arr[i] === compare)	return i;
		}
		return -1;
	},
	/**
	 * 设置对象透明度
	 * @id setOpacity
	 * @param {Object} HTML标签的id或者Dom对象
	 * @param {Nunber} 透明值
	 * @return {Object} Dom HTMLElement对象
	 */
	setOpacity:function(el, num){
		el = this.$(el);
		document.all?
			el.style.filter = "Alpha(Opacity=" + num + ")":
			el.style.opacity = num/100;
		return el;
	},
	/**
	 * 对象透明渐出
	 * @id fadein
	 * @param {Object} HTML标签的id或者Dom对象
	 * @param {Nunber} 延时值
	 * @param {Nunber} 透明步长
	 * @param {Function} 回调函数(可选)
	 * @return {Number} 时间器
	 */
	fadein: function(el, speed, step, callback) {
        speed = speed || 1;
        step = step || 1;
		el = this.$(el);
        var num = 0;
        var _this = this;
        var timer = setInterval(function() {
            _this.setOpacity(el, (num += step));
            if (num >= 100) {
                clearInterval(timer);
                callback && callback(el);
            }
        },speed);
        return timer;
    },
	/**
	 * 对象透明渐隐
	 * @id fadeout
	 * @param {Object} HTML标签的id或者Dom对象
	 * @param {Nunber} 延时值
	 * @param {Nunber} 透明步长
	 * @param {Function} 回调函数(可选)
	 * @return {Number} 时间器
	 */
	fadeout: function(el, speed, step, callback) {
        speed = speed || 1;
        step = step || 1;
		el = this.$(el);
        var num = 100;
        var _this = this;
        var timer = setInterval(function() {
            _this.setOpacity(el, (num -= step));
            if (num <= 0) {
                clearInterval(timer);
                callback && callback(el);
            }
        },speed);
        return timer;
    },
	/**
	 * 对象滑动
	 * @id slide
	 * @param {Object} HTML标签的id或者Dom对象
	 * @param {String} 滑动样式
	 * @param {Nunber} 开始位置
	 * @param {Nunber} 结束位置
	 * @param {Nunber} 滑动速度
	 * @param {Number} 时间器
	 */
	slide: function(el, style, start, end, speed, callback, extra) {
		el = this.$(el);
		speed = speed || 0.1;
		var prefix = "";
		var dom = el;
		
		if(style === "height" || style === "width" || style === "top" || style === "bottom" || style === "left" || style === "right" ){
			el = el.style;
			prefix = "px";
		}

        var timer = setInterval(function(){
			if (start > end) {
				start -= Math.ceil((start - end) * speed);
				el[style] = start + prefix;
				extra && extra(dom);
				if (start <= end) {
					clearInterval(timer);
					callback && callback(dom);
				}
			} else {
				start += Math.ceil((end - start) * speed);
				el[style] = start + prefix;
				extra && extra(dom);
				if (start >= end) {
					clearInterval(timer);
					callback && callback(dom);
				}
			}
		}, 1);
		return timer;
    },
	/**
	 * JSON
	 * @id JSON
	 * stringify:将字面量对象转为string
	 * parse:将string转为字面量对象
	 */
	JSON:function() {
        function f(n) { return n < 10 ? '0' + n : n; }
        Date.prototype.toJSON = function() { return this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z'; };
        var m = { '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"': '\\"', '\\': '\\\\' }; function stringify(value, whitelist) {
            var a, i, k, l, r = /["\\\x00-\x1f\x7f-\x9f]/g, v; switch (typeof value) {
                case 'string': return r.test(value) ? '"' + value.replace(r, function(a) {
                    var c = m[a]; if (c) { return c; }
                    c = a.charCodeAt(); return '\\u00' + Math.floor(c / 16).toString(16) +(c % 16).toString(16);
                }) + '"' : '"' + value + '"'; case 'number': return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': return String(value); case 'object': if (!value) { return 'null'; }
                    if (typeof value.toJSON === 'function') { return stringify(value.toJSON()); }
                    a = []; if (typeof value.length === 'number' && !(value.propertyIsEnumerable('length'))) {
                        l = value.length; for (i = 0; i < l; i += 1) { a.push(stringify(value[i], whitelist) || 'null'); }
                        return '[' + a.join(',') + ']';
                    }
                    if (whitelist) { l = whitelist.length; for (i = 0; i < l; i += 1) { k = whitelist[i]; if (typeof k === 'string') { v = stringify(value[k], whitelist); if (v) { a.push(stringify(k) + ':' + v); } } } } else { for (k in value) { if (typeof k === 'string') { v = stringify(value[k], whitelist); if (v) { a.push(stringify(k) + ':' + v); } } } }
                    return '{' + a.join(',') + '}';
            } 
        }
        return { stringify: stringify, parse: function(text, filter) {
            var j; function walk(k, v) {
                var i, n; if (v && typeof v === 'object') { for (i in v) { if (Object.prototype.hasOwnProperty.apply(v, [i])) { n = walk(i, v[i]); if (n !== undefined) { v[i] = n; } else { delete v[i]; } } } }
                return filter(k, v);
            }
            if (/^[\],:{}\s]*$/.test(text.replace(/\\["\\\/bfnrtu]/g, '@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { j = eval('(' + text + ')'); return typeof filter === 'function' ? walk('', j) : j; }
            throw new SyntaxError('parseJSON');
        } 
        };
    }(),
	/**
	 * Cookie
	 * @id Cookie
	 */
	Cookie:{
		write: function(name, value, exp, path, domain, secure) {
			var cookieValue = name + "=" + value;
			if (exp) {
				var dt = new Date();
				dt.setTime(dt.getTime() + (exp * 1000));
				cookieValue += "; expires=" + dt.toGMTString();
			}
			if (path) {
				cookieValue += "; path=" + path;
			}
			if (domain){
				cookieValue += "; domain=" + domain;
			}
			if (secure){
				cookieValue += "; secure";
			}
			document.cookie = cookieValue;

		},
		rewrite: function(name, key, keyVal, exp, path, domain, secure){
			var str = key;
			if(keyVal){
				var cookie = this.read(name);
				var reg = new RegExp("\\b" + key +"=([^&]*)\\b","g");
				str = cookie.replace(reg,function(m1, m2){
					return m1.replace(m2,keyVal);
				})
			}
			this.write(name, str, exp, path, domain, secure);
		},
		setDay: function(name, value, exp, path){
			this.write(name, value, (exp * 24 * 60 * 60), path);
		},
		setHour: function(name, value, exp, path){
			this.write(name, value, (exp * 60 * 60), path);
		},
		setMin: function(name, value, exp, path){
			this.write(name, value, (exp * 60), path);
		},
		setSec: function(name, value, exp, path){
			this.write(name, value, (exp), path);
		},
		read: function(name, key) {
			var cookieValue = "";
			var search = name + "=";
			if (document.cookie.length > 0) {
				offset = document.cookie.indexOf(search);
				if (offset != -1) {
					offset += search.length;
					end = document.cookie.indexOf(";", offset);
					if (end == -1) {
						end = document.cookie.length;
					}
					cookieValue = document.cookie.substring(offset, end);
				}

			}
			if(key){
				return new Kg.Param().parse(cookieValue)[key];
			}
			return cookieValue;
		},
		remove: function(name, path, domain) {
			var cookie = name + "=";
			if (path)
				cookie += '; path=' + path;
			if (domain)
				cookie += ';domain=' + domain;
			cookie += '; expires=Fri, 02-Jan-1970 00:00:00 GMT';
			document.cookie = cookie;
		}
	},
	Param:function(){
		var arr = [];
		var o = {};
		this.parse = function(str){
			var a = str.split("&");
			for(var i = 0, l = a.length; i < l; i++){
				var k = a[i].split("=");
				o[k[0]] = k[1];
			}
			return o;
		};
		this.toString = function(filter){
			filter = filter || "&";
			return arr.join(filter);
		};
		this.add = function(key, val){
			var prm = key + "=" + val;
			arr.push(prm);
			return this;
		}
	},
	Ajax: function(method, url, async, args, callback, error, docType) {
		var params = args;
		async = async == null?true:async;
		if(args){
			if(typeof args === "object"){
				var str = "";
				for(var i in args){
					str += i + "=" + args[i] + "&";
				}
				params = str.substr(0, str.length - 1);
			}
		}

        method = method ? method.toUpperCase() : "POST";
        docType = docType ? docType: "text";
        var XMLHttp = null;
        if (window.XMLHttpRequest && !(window.ActiveXObject)) {
            XMLHttp = new XMLHttpRequest();
        } else if (window.ActiveXObject) {
            try {
                XMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
            } catch(otherMSIE) {
                try {
                    XMLHttp = new ActiveXObject("Msxml2.XMLHTTP");
                } catch(NoSupport) {
                    XMLHttp = null;
                }
            }
        }
        
        XMLHttp.onreadystatechange = function() {
            if (XMLHttp.readyState == 4) {
                if (XMLHttp.status == 200 || XMLHttp.status == 0) {
                    var param = null;
                    switch (docType) {
                    case "xml":
                        param = XMLHttp.responseXML;
                        break;
                    case "json":
                        param = Kg.JSON.parse(XMLHttp.responseText);
                        break;
                    default:
                        param = XMLHttp.responseText;
                    }
                    callback && callback(param, XMLHttp);
                    XMLHttp = null;
                } else {
					error && error();
				}
            }
        };

		if (method == "GET") {
            XMLHttp.open(method, url + "?" + (params || ''), async);
            XMLHttp.send(null);
        } else {
            XMLHttp.open(method, url, async);
            XMLHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            XMLHttp.send(params);
        }
    },
	get:function(url, params, callback, error, async){
		this.Ajax("get", url, async, params, callback, error);
	},
	post:function(url, params, callback, error, async){
		this.Ajax("post", url, async, params, callback, error);
	},
	getJSON:function(url, params, callback, error, async){
		this.Ajax("get", url, async, params, callback, error, "json");
	},
	postJSON:function(url, params, callback, error, async){
		this.Ajax("post", url, async, params, callback, error, "json");
	},
	loadScript:function(url, args, callback){
		var params = args || "";
		if(args && (typeof args === "object")){
			var str = "";
			for(var i in args){
				str += i + "=" + args[i] + "&";
			}
			params = str.substr(0, str.length - 1);
		};
		var script = document.createElement("script");
		script.type = 'text/javascript';
		script.src = url + "?" + params;
		script.onload = script.onreadystatechange = function(){
			if(!this.readyState || (this.readyState == "complete" || this.readyState == "loaded")){
				callback && callback();
				script.onreadystatechange = script.onload = null;
				script = null;
			}
		};
		document.getElementsByTagName("head")[0].appendChild(script);
	},
	/*flash异步跨域*/
	flash:{
		ready:false,
		init:function(){
			this.ready = true;
		},
		getStr:function(name, flashUrl, width, height, params) {
				var str = "";
				var o = {
					"flashvars" : '',
					"wmode" : ''
				};
				params = params || {};
				Kg.extend(o, params, true);
				str += '<object id="' + name + '" name="' + name + '" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10.0.32" width="' + width + '" height="' + height + '">';
				str += '<param name="bgColor" value="#666666" />';
				str += '<param name="movie" value="' + flashUrl + '" />';
				str += '<param name="flashvars" value="' + o.flashvars + '" />';
				str += '<param name="quality" value="high" />';
				str += '<param name="allowScriptAccess" value="always" />';
				str += '<param name="WMODE" value="' + o.wmode + '"/>';
				str += '<embed name="' + name + '" src="' + flashUrl + '" width="' + width + '"  height="' + height + '" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="' + o.flashvars + '" type="application/x-shockwave-flash" wmode="' + o.wmode + '" ></embed>';
				str += '</object>';
				return str;
		},
		write:function(name, flashUrl, width, height, params){
			document.write(this.getStr(name, flashUrl, width, height, params));
		},
		getObj:function(name){
			if (Kg.UA.FF) {
				return document[name][1];
			} else if(Kg.UA.Ie){
				return window[name];
			} else {
				return window[name][1];	
			}
		},
		Ajax:function(url, params, method, callback){
			var _this = this;
			var el = Kg.$("Ajax-flash-object");
			if(el){
				(this.ready == true) && this.getObj('KugouAjaxFlash').SetParameters(url, params, method, callback);
			} else{
				var projectName = location.pathname.match(/^\/(\w+)\//)[1];
				var el = document.createElement("div");
				el.id = "Ajax-flash-object";
				document.body.appendChild(el);
				el.innerHTML = this.getStr('KugouAjaxFlash', '/' + projectName + '/view/flash/Httpreq.swf', 1, 1, {
					"flashvars":"ini=Kg.flash.init"
				});
	
				var timer = setInterval(function(){
					var flashObj = _this.getObj('KugouAjaxFlash');
					if(flashObj && flashObj.SetParameters){
						clearInterval(timer);
						flashObj.SetParameters(url, params, method, callback);
					}
				},100)
			}
		}
	}
};